package com.asman.worker.widgets.multiFile

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.asman.base.lib.glide.GlideApp
import com.asman.customerview.SquareImageView
import com.asman.customerview.extensions.isMulti
import com.asman.oss.my.OSSUpload
import com.asman.worker.R
import ossZip
import showToast

class MultiImageUploadLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private var ivImg: SquareImageView
    private var ivDelete: ImageView
    private var progressBar: ProgressBar
    private var tvUploadResult: TextView
    private var ivHover: SquareImageView
    private var ivPlayer: ImageView

    lateinit var data: ImageUploadData

    init {
        View.inflate(context, R.layout.layout_upload_image, this)
        ivImg = findViewById(R.id.iv_img)
        ivHover = findViewById(R.id.iv_hover)
        ivDelete = findViewById(R.id.iv_delete)
        progressBar = findViewById(R.id.progressBar)
        tvUploadResult = findViewById(R.id.tv_upload_result)
        ivPlayer = findViewById(R.id.iv_play)
    }

    abstract class OnCallBack {
        open fun onAddClickListener() {}
        open fun onDeleteClickListener(data: ImageUploadData) {}
        open fun onImageListener(data: ImageUploadData) {}
    }

    var callBack: OnCallBack? = null

    fun setOnCallBackListener(callBack: OnCallBack?) {
        this.callBack = callBack
    }

    fun updateProgress(uploadProgress: Int) {
        data.uploadProgress = uploadProgress
        progressBar.progress = uploadProgress
    }

    fun initType(data: ImageUploadData) {
        this.data = data
        when (data.status) {
            0 -> { //添加
                ivDelete.visibility = View.GONE
                progressBar.visibility = View.GONE
                tvUploadResult.visibility = View.GONE
                ivHover.visibility = View.GONE
                ivImg.background = context.getDrawable(R.drawable.selector_stroke_click_small)
                ivImg.setOnClickListener {
                    //点击添加图片
                    callBack?.onAddClickListener()
                }
            }
            1, 2 -> { //1:已添加，未开始上传   2:正在上传
                ivDelete.visibility = View.VISIBLE
                progressBar.visibility = View.VISIBLE
                tvUploadResult.visibility = View.GONE
                ivHover.visibility = View.VISIBLE
                GlideApp.with(context).load(data.localPath).into(ivImg)
                ivDelete.setOnClickListener {
                    onDestroy()
                    //删除本图片，刷新，并且停止上传
                    callBack?.onDeleteClickListener(data)
                }
                ivImg.setOnClickListener {
                    //查看图片
                    callBack?.onImageListener(data)
                }
                if (data.status == 1) { //1:已添加，未开始上传
                    uploadFile(data.localPath)
                }
            }
            3 -> { //上传完成
                progressBar.visibility = View.GONE
                tvUploadResult.visibility = View.GONE
                ivHover.visibility = View.GONE
                ivDelete.visibility = View.VISIBLE
                if (data.localPath.isNullOrEmpty()) {
                    val url = data.url.ossZip(100f, 100f, 2f)
                    //如果标记为上传文成，但是localPath为空，这说明谁回写数据
                    GlideApp.with(context).load(url).placeholder(R.color._f0f0f0).into(ivImg)
                } else {
                    GlideApp.with(context).load(data.localPath).into(ivImg)
                }
                ivDelete.setOnClickListener {
                    onDestroy()
                    //删除本图片，刷新，并且停止上传
                    callBack?.onDeleteClickListener(data)
                }
                ivImg.setOnClickListener {
                    //查看图片
                    callBack?.onImageListener(data)
                }
                if (data.localPath?.isMulti() == true) {
                    ivPlayer.visibility = View.VISIBLE
                } else {
                    ivPlayer.visibility = View.GONE
                }
            }
            4 -> { //上传失败
                ivDelete.visibility = View.VISIBLE
                progressBar.visibility = View.GONE
                ivHover.visibility = View.VISIBLE
                tvUploadResult.visibility = View.VISIBLE
                GlideApp.with(context).load(data.localPath).into(ivImg)
                ivDelete.setOnClickListener {
                    onDestroy()
                    //删除本图片，刷新，并且停止上传
                    callBack?.onDeleteClickListener(data)
                }
                ivImg.setOnClickListener {
                    uploadFile(data.localPath) //重新上传
                }
            }
        }
        requestLayout()
    }

    var bucketName: String? = null
    var endpoint: String? = null

    fun initOSS(bucketName: String?, endpoint: String?) {
        this.bucketName = bucketName
        this.endpoint = endpoint
    }

    var task: OSSAsyncTask<PutObjectResult>? = null

    //开始上传文件
    private fun uploadFile(localPath: String?) {
        if (localPath.isNullOrEmpty()) return
        if (bucketName == null || endpoint == null) {
            showToast("配置信息有误")
            return
        }
        data.status = 2
        data.localPath = localPath
        initType(data)
        task = OSSUpload.get(bucketName, endpoint)
            .asyncPutImage(data.localPath, object : OSSUpload.OnUploadListener {
                override fun onProgress(progress: Int) {
                    updateProgress(progress)
                }

                @SuppressLint("CheckResult")
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult?) {
                    data.status = 3
                    updateProgress(100)
                    data.url = request?.objectKey
                    initType(data)
                }

                override fun onFailed(
                    request: PutObjectRequest?,
                    clientExcepion: ClientException?,
                    serviceException: ServiceException?
                ) {
                    if (task?.isCanceled != null && !task?.isCanceled!!) {
                        data.status = 4
                        updateProgress(0)
                        initType(data)
                    }
                }
            })
    }

    //停止上传
    fun onDestroy() {

        task?.cancel()
    }
}